/*
 * Copyright @2011 Dnbiz. All rights reserved.
 */
package com.dnbiz.api.sdk.util;

import java.io.IOException;

import org.apache.log4j.Logger;

import com.dnbiz.api.sdk.Api;
import com.dnbiz.api.sdk.ApiException;
import com.dnbiz.api.sdk.ApiFail;
import com.dnbiz.api.sdk.ApiFile;
import com.dnbiz.api.sdk.ApiParameter;
import com.dnbiz.api.sdk.ApiResult;

/**
 * <pre>
 * 请求API操作，并获得API结果
 * </pre>
 * @author HuangFeng(2011-1-21)
 */
public class RequestUtil {

	private static Logger log = Logger.getLogger(RequestUtil.class);

	/**
	 * Request Get方式请求
	 * @author HuangFeng(2011-1-26)
	 * @param apiurl API URL
	 * @return 响应结果
	 * @throws ApiException
	 */
	public static final ApiResult get(String apiurl) throws ApiException
	{
		String rstr = "";
		log.info("调用API["  + apiurl + "]");
		try {
			rstr = WebUtil.doGet(apiurl, Api._ENCODE);
			log.info("返回结果["  + rstr + "]");
			return parseApiResult(apiurl, rstr);
		} catch (IOException e) {
			log.error("访问API[" + apiurl + "]错误：", e);
			throw new ApiException(e);
		}
	}
	
	/**
	 * 一般Request Post提交请求 
	 * @author HuangFeng(2011-1-26)
	 * @param apiurl API URL
	 * @param params 提交参数 <code>is not null</code>
	 * @return 响应结果
	 * @throws ApiException
	 */
	public static final ApiResult post(String apiurl, ApiParameter<String, String> params) throws ApiException
	{
		String rstr = "";
		log.info("调用API["  + apiurl + "]");
		try {
			rstr = WebUtil.doPost(apiurl, params, Api._ENCODE);
			log.info("返回结果["  + rstr + "]");
			return parseApiResult(apiurl, rstr);
		} catch (IOException e) {
			log.error("访问API[" + apiurl + "]错误：", e);
			throw new ApiException(e);
		}
	}
	
	/**
	 * Request 文件上传 
	 * @author HuangFeng(2011-1-26)
	 * @param apiurl API URL
	 * @param params 一般文本参数
	 * @param fileParams 上传文件参数
	 * @return 响应结果
	 * @throws ApiException
	 */
	public static ApiResult upload(String apiurl, ApiParameter<String, String> params , ApiParameter<String, ApiFile> fileParams) throws ApiException
	{
		String rstr = "";
		log.info("调用API["  + apiurl + "]");
		try {
			rstr = WebUtil.doPost(apiurl, params, fileParams, Api._ENCODE);
			log.info("返回结果["  + rstr + "]");
			return parseApiResult(apiurl, rstr);
		} catch (IOException e) {
			log.error("访问API[" + apiurl + "]错误：", e);
			throw new ApiException(e);
		}
	}
	
	/**
	 * 响应结果处理
	 * @author HuangFeng(2011-1-26)
	 */
	private static ApiResult parseApiResult(String apiurl, String resultStr) throws ApiException
	{
		ApiResult result = new ApiResult();
		result.setApiurl(apiurl);
		//{"err":{"code":"303602","msg":"同步商品失败"},"stat":"fail"}
		if(isFail(resultStr))
		{
			result.setFlag(ApiResult.Flag.FAIL);
			String fail = resultStr.substring(7, resultStr.length() - 15);
			ApiFail apiFail = JsonUtil.getClassEntityByString(fail, ApiFail.class);
			result.setResult(apiFail);
			throw new ApiException(apiFail.toString());
		}
		else if(isOk(resultStr))
		{
			result.setFlag(ApiResult.Flag.OK);
			String okstr = resultStr.substring(0, resultStr.length() - 13) + "}";
			result.setResult(okstr);
			//StringUtil.getLowerCaseRemoveUnderline(okstr));
		}
		
		//{"result":{"flag":1,"product_id":82},"stat":"ok"}
		result.setFormat(Api._FORMAT);
		return result;
	}
	
	private static boolean isFail(String resultStr)
	{
		if(resultStr.startsWith("{\"err\"") && resultStr.endsWith("\"stat\":\"fail\"}"))
		{
			return true;
		}
		
		return false;
	}
	
	private static boolean isOk(String resultStr)
	{
		if(resultStr.endsWith("\"stat\":\"ok\"}"))
		{
			return true;
		}
		
		return false;
	}
}
